<template>
  <div class="purchase-order-table">
    <el-table
      v-loading="loading"
      :data="orders"
      :stripe="stripe"
      :border="border"
      :size="size"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange"
      @row-click="handleRowClick"
      :row-class-name="getRowClassName"
    >
      <!-- 选择列 -->
      <el-table-column 
        v-if="showSelection"
        type="selection" 
        width="55" 
        :selectable="isSelectable"
      />

      <!-- 索引列 -->
      <el-table-column 
        v-if="showIndex"
        type="index" 
        label="序号" 
        width="60"
        :index="getIndex"
      />

      <!-- 紧急程度列 -->
      <el-table-column 
        v-if="showUrgency"
        label="紧急程度" 
        width="100"
        align="center"
      >
        <template #default="{ row }">
          <div class="urgency-indicator">
            <span v-if="isUrgent(row)" class="urgency-badge urgent" title="超过1天未处理">🚨</span>
            <span v-else-if="isHighPriority(row)" class="urgency-badge high" title="高优先级">⚡</span>
            <span v-else-if="isLargeAmount(row)" class="urgency-badge large" title="大额订单">💰</span>
          </div>
        </template>
      </el-table-column>

      <!-- 订单号列 -->
      <el-table-column 
        prop="orderNumber" 
        label="订单号" 
        width="160" 
        :fixed="columns.orderNumber?.fixed"
        :sortable="columns.orderNumber?.sortable"
        v-if="isColumnVisible('orderNumber')"
      >
        <template #default="{ row }">
          <el-link 
            type="primary" 
            @click="handleOrderClick(row)"
            :underline="false"
          >
            {{ row.orderNumber }}
          </el-link>
        </template>
      </el-table-column>

      <!-- 供应商列 -->
      <el-table-column 
        prop="supplierName" 
        label="供应商" 
        width="200"
        :sortable="columns.supplierName?.sortable"
        show-overflow-tooltip
        v-if="isColumnVisible('supplierName')"
      />

      <!-- 订单类型列 -->
      <el-table-column 
        prop="orderType" 
        label="订单类型" 
        width="120"
        :sortable="columns.orderType?.sortable"
        v-if="isColumnVisible('orderType')"
      >
        <template #default="{ row }">
          <el-tag :type="getOrderTypeTagType(row.orderType)">
            {{ row.orderType }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 优先级列 -->
      <el-table-column 
        prop="priority" 
        label="优先级" 
        width="100"
        :sortable="columns.priority?.sortable"
        v-if="isColumnVisible('priority')"
      >
        <template #default="{ row }">
          <el-tag :type="getPriorityTagType(row.priority)" size="small">
            {{ row.priority }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 订单金额列 -->
      <el-table-column 
        prop="totalAmount" 
        label="订单金额" 
        width="120" 
        align="right"
        :sortable="columns.totalAmount?.sortable"
        v-if="isColumnVisible('totalAmount')"
      >
        <template #default="{ row }">
          <span :class="['amount', { 'large-amount': isLargeAmount(row) }]">
            ¥{{ formatCurrency(row.totalAmount) }}
          </span>
        </template>
      </el-table-column>

      <!-- 状态列 -->
      <el-table-column 
        prop="status" 
        label="状态" 
        width="120"
        :sortable="columns.status?.sortable"
        v-if="isColumnVisible('status')"
      >
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.status)">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 创建时间列 -->
      <el-table-column 
        prop="createTime" 
        label="创建时间" 
        width="160"
        :sortable="columns.createTime?.sortable"
        v-if="isColumnVisible('createTime')"
      >
        <template #default="{ row }">
          {{ formatDateTime(row.createTime) }}
        </template>
      </el-table-column>

      <!-- 创建人列 -->
      <el-table-column 
        prop="creator" 
        label="创建人" 
        width="120"
        :sortable="columns.creator?.sortable"
        v-if="isColumnVisible('creator')"
      />

      <!-- 提交时间列 -->
      <el-table-column 
        label="提交时间" 
        width="140"
        :sortable="columns.submitTime?.sortable"
        v-if="isColumnVisible('submitTime')"
      >
        <template #default="{ row }">
          <div v-if="row.submitTime" class="submit-time">
            <div>{{ formatDate(row.submitTime) }}</div>
            <div class="time-elapsed" :class="getElapsedTimeClass(row.submitTime)">
              {{ getElapsedTime(row.submitTime) }}
            </div>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>

      <!-- 更新时间列 -->
      <el-table-column 
        prop="updateTime" 
        label="更新时间" 
        width="160"
        :sortable="columns.updateTime?.sortable"
        v-if="isColumnVisible('updateTime')"
      >
        <template #default="{ row }">
          {{ formatDateTime(row.updateTime) }}
        </template>
      </el-table-column>

      <!-- 预期交货日期列 -->
      <el-table-column 
        prop="expectedDeliveryDate" 
        label="预期交货" 
        width="120"
        :sortable="columns.expectedDeliveryDate?.sortable"
        v-if="isColumnVisible('expectedDeliveryDate')"
      >
        <template #default="{ row }">
          {{ formatDate(row.expectedDeliveryDate) }}
        </template>
      </el-table-column>

      <!-- 自定义列 -->
      <template v-for="column in customColumns" :key="column.prop">
        <el-table-column 
          :prop="column.prop"
          :label="column.label"
          :width="column.width"
          :min-width="column.minWidth"
          :fixed="column.fixed"
          :sortable="column.sortable"
          :align="column.align"
        >
          <template #default="scope">
            <slot 
              :name="`column-${column.prop}`" 
              v-bind="scope"
            >
              {{ scope.row[column.prop] }}
            </slot>
          </template>
        </el-table-column>
      </template>

      <!-- 操作列 -->
      <el-table-column 
        label="操作" 
        :width="actionWidth"
        :fixed="actionFixed"
        v-if="showActions"
      >
        <template #default="{ row }">
          <div class="action-buttons">
            <!-- 默认操作按钮 -->
            <el-button 
              v-if="showAction('view')"
              size="small" 
              type="primary" 
              @click="handleAction('view', row)"
            >
              详情
            </el-button>
            <el-button 
              v-if="showAction('edit') && canEdit(row)"
              size="small" 
              type="warning" 
              @click="handleAction('edit', row)"
            >
              编辑
            </el-button>
            <el-button 
              v-if="showAction('submit') && canSubmit(row)"
              size="small" 
              type="primary" 
              @click="handleAction('submit', row)"
            >
              提交
            </el-button>
            <el-button 
              v-if="showAction('approve') && canApprove(row)"
              size="small" 
              type="success" 
              @click="handleAction('approve', row)"
            >
              审批
            </el-button>
            <el-button 
              v-if="showAction('reject') && canApprove(row)"
              size="small" 
              type="danger" 
              @click="handleAction('reject', row)"
            >
              拒绝
            </el-button>

            <!-- 更多操作下拉菜单 -->
            <el-dropdown 
              v-if="hasMoreActions(row)"
              @command="(command: string) => handleDropdownCommand(command, row)"
            >
              <el-button size="small" type="info">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item 
                    v-if="showAction('withdraw') && canWithdraw(row)"
                    command="withdraw"
                  >
                    撤回
                  </el-dropdown-item>
                  <el-dropdown-item 
                    v-if="showAction('copy')"
                    command="copy"
                  >
                    复制
                  </el-dropdown-item>
                  <el-dropdown-item 
                    v-if="showAction('print')"
                    command="print"
                  >
                    打印
                  </el-dropdown-item>
                  <el-dropdown-item 
                    v-if="showAction('export')"
                    command="export"
                  >
                    导出
                  </el-dropdown-item>
                  <el-dropdown-item 
                    v-if="showAction('delete') && canDelete(row)"
                    command="delete"
                    divided
                  >
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <!-- 自定义操作插槽 -->
            <slot name="actions" :row="row" />
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { ArrowDown } from '@element-plus/icons-vue'
import type { PurchaseOrderDto } from '@/types/console'

// Props
interface Props {
  // 数据
  orders: PurchaseOrderDto[]
  loading?: boolean

  // 表格样式
  stripe?: boolean
  border?: boolean
  size?: 'large' | 'default' | 'small'

  // 列配置
  columns?: Record<string, { 
    visible?: boolean
    sortable?: boolean | string
    fixed?: boolean | string
  }>
  customColumns?: Array<{
    prop: string
    label: string
    width?: number
    minWidth?: number
    fixed?: boolean | string
    sortable?: boolean | string
    align?: string
  }>

  // 功能配置
  showSelection?: boolean
  showIndex?: boolean
  showUrgency?: boolean
  showActions?: boolean

  // 操作配置
  actions?: string[]
  actionWidth?: number
  actionFixed?: boolean | string

  // 权限配置
  permissions?: {
    edit?: (row: PurchaseOrderDto) => boolean
    delete?: (row: PurchaseOrderDto) => boolean
    approve?: (row: PurchaseOrderDto) => boolean
  }

  // 分页配置
  pagination?: {
    pageIndex: number
    pageSize: number
  }
}

const props = withDefaults(defineProps<Props>(), {
  loading: false,
  stripe: true,
  border: true,
  size: 'default',
  showSelection: false,
  showIndex: false,
  showUrgency: false,
  showActions: true,
  actions: () => ['view', 'edit', 'submit', 'approve', 'reject', 'withdraw', 'copy', 'print', 'export', 'delete'],
  actionWidth: 200,
  actionFixed: 'right',
  columns: () => ({
    orderNumber: { visible: true, sortable: true, fixed: 'left' },
    supplierName: { visible: true, sortable: true },
    orderType: { visible: true, sortable: true },
    priority: { visible: true, sortable: true },
    totalAmount: { visible: true, sortable: true },
    status: { visible: true, sortable: true },
    createTime: { visible: true, sortable: true },
    creator: { visible: true, sortable: true },
    submitTime: { visible: false, sortable: true },
    updateTime: { visible: false, sortable: true },
    expectedDeliveryDate: { visible: false, sortable: true }
  })
})

// Emits
const emit = defineEmits<{
  'selection-change': [selection: PurchaseOrderDto[]]
  'sort-change': [{ column: any; prop: string; order: string }]
  'row-click': [row: PurchaseOrderDto]
  'order-click': [row: PurchaseOrderDto]
  'action': [action: string, row: PurchaseOrderDto]
}>()

// 计算属性
const isColumnVisible = (columnName: string) => {
  return props.columns?.[columnName]?.visible !== false
}

const showAction = (action: string) => {
  return props.actions.includes(action)
}

// 方法
const handleSelectionChange = (selection: PurchaseOrderDto[]) => {
  emit('selection-change', selection)
}

const handleSortChange = (sortInfo: { column: any; prop: string; order: string }) => {
  emit('sort-change', sortInfo)
}

const handleRowClick = (row: PurchaseOrderDto) => {
  emit('row-click', row)
}

const handleOrderClick = (row: PurchaseOrderDto) => {
  emit('order-click', row)
}

const handleAction = (action: string, row: PurchaseOrderDto) => {
  emit('action', action, row)
}

const handleDropdownCommand = (command: string, row: PurchaseOrderDto) => {
  emit('action', command, row)
}

// 权限判断
const canEdit = (row: PurchaseOrderDto) => {
  if (props.permissions?.edit) {
    return props.permissions.edit(row)
  }
  return ['草稿', '已拒绝'].includes(row.status)
}

const canSubmit = (row: PurchaseOrderDto) => {
  return row.status === '草稿'
}

const canWithdraw = (row: PurchaseOrderDto) => {
  return row.status === '待审批'
}

const canApprove = (row: PurchaseOrderDto) => {
  if (props.permissions?.approve) {
    return props.permissions.approve(row)
  }
  return ['待审批', '审批中'].includes(row.status)
}

const canDelete = (row: PurchaseOrderDto) => {
  if (props.permissions?.delete) {
    return props.permissions.delete(row)
  }
  return ['草稿', '已拒绝'].includes(row.status)
}

const hasMoreActions = (row: PurchaseOrderDto) => {
  const moreActions = ['withdraw', 'copy', 'print', 'export', 'delete']
  return moreActions.some(action => 
    showAction(action) && 
    (action === 'copy' || action === 'print' || action === 'export' || 
     (action === 'withdraw' && canWithdraw(row)) ||
     (action === 'delete' && canDelete(row)))
  )
}

// 选择判断
const isSelectable = (row: PurchaseOrderDto) => {
  // 可以根据业务需求自定义选择条件
  return true
}

// 获取索引
const getIndex = (index: number) => {
  if (props.pagination) {
    return (props.pagination.pageIndex - 1) * props.pagination.pageSize + index + 1
  }
  return index + 1
}

// 行样式判断
const getRowClassName = ({ row }: { row: PurchaseOrderDto }) => {
  const classes = []
  if (isUrgent(row)) classes.push('urgent-row')
  else if (isHighPriority(row)) classes.push('high-priority-row')
  else if (isLargeAmount(row)) classes.push('large-amount-row')
  return classes.join(' ')
}

// 紧急程度判断
const isUrgent = (order: PurchaseOrderDto) => {
  if (!order.submitTime) return false
  const submitDate = new Date(order.submitTime)
  const now = new Date()
  const diffHours = (now.getTime() - submitDate.getTime()) / (1000 * 60 * 60)
  return diffHours > 24
}

const isHighPriority = (order: PurchaseOrderDto) => {
  return ['紧急', '高'].includes(order.priority || '')
}

const isLargeAmount = (order: PurchaseOrderDto) => {
  return (order.totalAmount || 0) > 100000
}

// 时间相关
const getElapsedTime = (submitTime: string) => {
  if (!submitTime) return ''
  const submitDate = new Date(submitTime)
  const now = new Date()
  const diffMs = now.getTime() - submitDate.getTime()
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
  const diffDays = Math.floor(diffHours / 24)
  
  if (diffDays > 0) {
    return `${diffDays}天前`
  } else if (diffHours > 0) {
    return `${diffHours}小时前`
  } else {
    const diffMinutes = Math.floor(diffMs / (1000 * 60))
    return `${diffMinutes}分钟前`
  }
}

const getElapsedTimeClass = (submitTime: string) => {
  if (!submitTime) return ''
  const submitDate = new Date(submitTime)
  const now = new Date()
  const diffHours = (now.getTime() - submitDate.getTime()) / (1000 * 60 * 60)
  
  if (diffHours > 24) return 'urgent'
  if (diffHours > 8) return 'warning'
  return 'normal'
}

// 格式化方法
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

const formatDate = (date: string) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN')
}

const formatCurrency = (amount: number) => {
  return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

// 样式判断
const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    '草稿': 'info',
    '待审批': 'warning',
    '审批中': 'primary',
    '已审批': 'success',
    '已拒绝': 'danger',
    '已撤回': 'info'
  }
  return typeMap[status] || 'info'
}

const getOrderTypeTagType = (orderType: string) => {
  const typeMap: Record<string, string> = {
    '标准采购': '',
    '紧急采购': 'danger',
    '框架采购': 'success',
    '补充采购': 'warning'
  }
  return typeMap[orderType] || ''
}

const getPriorityTagType = (priority: string) => {
  const typeMap: Record<string, string> = {
    '低': 'info',
    '中': '',
    '高': 'warning',
    '紧急': 'danger'
  }
  return typeMap[priority] || ''
}
</script>

<style scoped>
.purchase-order-table {
  width: 100%;
}

.urgency-indicator {
  display: flex;
  justify-content: center;
}

.urgency-badge {
  font-size: 1.2rem;
  padding: 0.25rem;
  border-radius: 4px;
}

.urgency-badge.urgent {
  background: #fef0f0;
  color: #f56c6c;
}

.urgency-badge.high {
  background: #fdf6ec;
  color: #e6a23c;
}

.urgency-badge.large {
  background: #f0f9ff;
  color: #67c23a;
}

.submit-time {
  text-align: center;
}

.time-elapsed {
  font-size: 0.75rem;
  padding: 0.125rem 0.25rem;
  border-radius: 4px;
  margin-top: 0.25rem;
}

.time-elapsed.normal {
  background: #f0f9ff;
  color: #409eff;
}

.time-elapsed.warning {
  background: #fdf6ec;
  color: #e6a23c;
}

.time-elapsed.urgent {
  background: #fef0f0;
  color: #f56c6c;
}

.amount {
  font-weight: 600;
  color: #67c23a;
}

.amount.large-amount {
  color: #e6a23c;
  font-weight: 700;
}

.action-buttons {
  display: flex;
  gap: 0.25rem;
  flex-wrap: wrap;
}

/* 表格行样式 */
:deep(.urgent-row) {
  background-color: #fef0f0 !important;
}

:deep(.high-priority-row) {
  background-color: #fdf6ec !important;
}

:deep(.large-amount-row) {
  background-color: #f0f9ff !important;
}

:deep(.urgent-row:hover) {
  background-color: #fde2e2 !important;
}

:deep(.high-priority-row:hover) {
  background-color: #faecd8 !important;
}

:deep(.large-amount-row:hover) {
  background-color: #e1effe !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .action-buttons {
    flex-direction: column;
    gap: 0.125rem;
  }

  .action-buttons .el-button {
    width: 100%;
    margin: 0;
  }
}
</style> 